package com.sleep.ruledemo.util;

import cn.hutool.core.util.ObjectUtil;
import lombok.experimental.UtilityClass;

import java.io.*;

@UtilityClass
public class DeepCopyUtil {
    /**
     * 通过对象序列化实现深拷贝
     * @param source 被拷贝的对象
     * @return 拷贝后的对象
     */
    public static <T extends Serializable> T deepCopy(T source) {
        if (source == null) {
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        try{
            // 将对象写入字节数组输出流
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(source);
            objectOutputStream.flush();

            // 从字节数组输入流读取对象
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            @SuppressWarnings("unchecked")
            T copiedObject = (T) objectInputStream.readObject();
            return copiedObject;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
                if (objectInputStream != null) {
                    objectInputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
     /**
       * @author Guo Ao
       * @date 2025/3/27 10:49
       * @description TODO
       * @param 
       * @return 
       */
    public static <T extends Serializable> T deepCopy2(T source) {
        return ObjectUtil.cloneByStream(source);
    }
    
     /**
       * @author Guo Ao
       * @date 2025/3/27 10:52
       * @description TODO
       * @params value
       * @return
       */
    public static String getStr(String value){
        return "";
    }

    public static String getStr2(String value){
        return "";
    }
}
